<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * 用户相关接口
 * @author Calvin<hongbinfu@163.com>
 * @readme  :返回结果请使用common_response
 * @help    :具体用法请参考https://github.com/chriskacerguis/codeigniter-restserver
 * @other   :
 *          GET ---  $this->get();
 *          POST --- $this->post();
 *          PUT --- $this->put();
  *         DELETE --- $this->delete();
 */
require(APPPATH.'libraries/Android_Controller.php');
class User_center extends Android_Controller
{

    //private $_find_pwd_vcode = "__FIND_PWD_VCODE__";
    private $_find_pwd_code = "__FIND_PWD_CODE__";
    private $_find_pwd_user = "__FIND_PWD_USER__";
    private $_find_pwd_account = "__FIND_PWD_ACCOUNT__";  //用户帐号

    public function  __construct() {
        parent::__construct();
        $services = array(
            'register_service',
            'login_service',
            'user_verify_service',
            'user_info_service'
        );
        $this->load->service($services);
        $this->load->library("form_validation");
        $this->config->load("form_validation");
    }

    public function index_get()
    {
        $this->common_response(1003);
    }

    /**
     * 用户注册
     */
    public function register_post() {
        $this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
        $this->form_validation->set_rules('password','', 'required|valid_password');
        $this->form_validation->set_rules('code','', 'required');
        if ($this->form_validation->run() === FALSE)
            $this->common_response(1003);

        $mobile = trim($this->input->post('mobile', TRUE));
        $password = $this->input->post('password',TRUE);
        $sms_vcode = $this->input->post("code",TRUE);

        $is_exist = $this->user_verify_service->check_user_by_phone($mobile);
        if ($is_exist) return $this->common_response(5009);

        $check_code = $this->user_verify_service->check_sms_code($sms_vcode, $mobile, 1, TRUE);
        if(empty($check_code))
            return $this->common_response($this->user_verify_service);

        $register = $this->register_service->register_by_phone($mobile, $password);
        if (empty($register))
            $this->common_response($this->register_service);

        $this->register_service->delete_register_log();
        $this->login_service->unset_tryout();
        //登录
        $this->login_service->login_by_uid($this->register_service->get_register_uid());
        return $this->common_response(0);
    }


    /**
     * ::注册用户::发送验证码
     * @return array
     */
    public function sms_code_post() {
        $this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');

        if ($this->form_validation->run() === FALSE)
            $this->common_response(1003);

        $mobile = trim($this->input->post("mobile",TRUE));
        $check = $this->register_service->check_phone_exists($mobile);

        if ($check)
            return $this->common_response(5009);

        $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_REGISTER);
        if ($send)
            return $this->common_response(0);

        return $this->common_response($this->user_verify_service);
    }

    /**
     * 登陆
     */
    public function login_post() {
        //清空找回密码的session
        if (isset($_SESSION[$this->_find_pwd_user])) {
            unset($_SESSION[$this->_find_pwd_code]);
            unset($_SESSION[$this->_find_pwd_user]);
        }

        $client_id = $this->post("client_id");
        if (empty($client_id))
            return $this->common_response(1003);

        $account = trim($this->input->post('account',true));
        $password = trim($this->input->post('password',true));
        if (empty($account) || empty($password))
            return $this->common_response(1003);

        $email_valid = $this->form_validation->valid_email($account);
        $phone_valid = $this->form_validation->valid_mobile_phone($account);
        if (empty($email_valid) && empty($phone_valid))
            return $this->common_response(1003);

        $user = (true === $email_valid) ?
            $this->login_service->check_login_by_email($account, $password):
            $this->login_service->check_login_by_phone($account, $password);

        if (empty($user)) {
            $this->login_service->add_login_error_log();
            return $this->common_response($this->login_service);
        }

        $this->login_service->login_by_data($user,0,0);

        $platform   = $this->post("platform");
        if (! in_array($platform, array("android", "ios", "pc"))) {
            $platform = "android";
        }
        
        //$this->login_service->login_uid = $user['id'];
        $add_fast_login = $this->login_service->fast_login_option($client_id,"",2, $platform);
        !isset($add_fast_login['token']) && $add_fast_login['token']="";
        return $this->common_response(0,NULL,array("fast_login_token"=>$add_fast_login['token'],"gid"=>$this->login_service->get_gid()));
    }

    /**
     * 快速登录 （免密码免账号）
     */
    public function fast_login_post(){
        $client_id  = $this->post("client_id");
        $token      = $this->post("login_token");
        $platform   = $this->post("platform");

        if (! in_array($platform, array("android", "ios", "pc"))) {
            $platform = "android";
        }

        if (empty($client_id) || empty($token))
            $this->common_response(1003);

        $check = $this->login_service->fast_login_option($client_id,$token,3, $platform);
        if ($check)
            return $this->common_response($this->login_service,NULL,array("fast_login_token"=>$check['token'],"gid"=>$this->login_service->get_gid()));

        return $this->common_response($this->login_service);
    }

    /**
     * v2.0
     * ::找回密码::发送验证码
     */
    public function pwd_code_post() {
        $account = trim($this->input->post('account', true));
        if (empty($account))
            return $this->common_response(1003);

        #判断是否是手机号
        $valid_mobile = $this->is_mobile($account);
        if ($valid_mobile) {
            $send = $this->user_verify_service->send_sms($account, User_verify_service::PROCESS_FIND_PASSWORD);
        } else {
            $send = $this->user_verify_service->send_email($account,User_verify_service::PROCESS_FIND_PASSWORD);
        }

        if ($send)
            return $this->common_response(0);

        return $this->common_response($this->user_verify_service);
    }

    /**
     * v2.0
     * ::找回密码::邮件或短信验证码检查
     */
    public function verification_code_post() {
        $this->form_validation->set_rules('code','', 'required');
        $this->form_validation->set_rules('account','', 'required');

        #参数失败
        if (! $this->form_validation->run())
            return $this->common_response(1003);

        $code = trim($this->input->post('code',true));
        $account = trim($this->input->post('account', true));

        #判断是否是手机号
        $valid_mobile = $this->is_mobile($account);
        if ($valid_mobile) {
            $check = $this->user_verify_service->check_sms_code($code, $account, User_verify_service::PROCESS_FIND_PASSWORD);
        } else {
            $check = $this->user_verify_service->check_email_verify_code($code, $account,User_verify_service::PROCESS_FIND_PASSWORD, false);
        }

        if (! $check)
            return $this->common_response($this->user_verify_service);

        #保存用户帐号供下一步设置新密码使用
        $this->session->set_userdata($this->_find_pwd_account, $account);
        return $this->common_response(0);
    }

    /**
     * v2.0
     * ::找回密码::重置密码
     */
    public function password_put() {
        $account = $_SESSION[$this->_find_pwd_account];
        if (empty($account))
            return $this->common_response(1008);

        $pwd = trim($this->put('password'));
        $pwd_valid = $this->form_validation->valid_password($pwd);

        if (! $pwd_valid)
            return $this->common_response(1003);

        $valid_mobile = $this->form_validation->valid_mobile_phone($account);
        $valid_email = $this->form_validation->valid_email($account);

        if ($valid_email) {
            $state = $this->user_info_service->update_user_info_by_email($account, array('password' => md5($pwd)));
        } else if($valid_mobile) {
            $state = $this->user_info_service->update_user_info_by_phone($account, array('password' => md5($pwd)));
        } else {
            return $this->common_response(1008);
        }

        if ($state)
            return $this->common_response(0);

         return $this->common_response($this->user_verify_service);
    }

    /**
     * 检测用户是否是手机号
     * @param $account 用户帐号 (email / mobile)
     * return bool 是否是手机号
     */
    private function is_mobile($account) {
        $valid_email = $this->form_validation->valid_email($account);
        $valid_mobile = $this->form_validation->valid_mobile_phone($account);
        #帐号错误
        if (! $valid_email && ! $valid_mobile)
            return $this->common_response(1003);

        if ($valid_mobile) {
            $check_user = $this->user_verify_service->check_user_by_phone($account);
        } else {
            $check_user = $this->user_verify_service->check_user_by_email($account);
        }

        if (! $check_user)
            return $this->common_response($this->user_verify_service);

        return $valid_mobile;
    }

    /**
     * 意见反馈
     */
    public function feedback_post() {
        $content = trim($this->input->post('content', true));
        if (empty($content))
            return $this->common_response(1003);

        $this->load->service("feedback_service");

        $v_contact = trim($this->input->post('contact', true));
        /*
        $title = trim($this->input->post('contact', true)) ?:
            sprintf($this->lang->line('feedback'),date('Ymd'));*/

        $contact = empty($v_contact) ? '' : array('contact' => $v_contact);
        $resp = $this->feedback_service->doadd($content, $contact);

        if (empty($resp))
            return $this->common_response($this->feedback_service);

        return $this->common_response(0);
    }

    /**
     * 检测版本
     */
    public function version_get() {
        $version = trim($this->input->get("v", true));
        $paltform = trim($this->input->get('paltform', true));
        if (empty($version))
            $this->common_response(1003);

        if ($paltform == 'ios') {
            $last_version = $this->config->item("ios_version");
            $down_url = $this->config->item("ios_download");
            $description = "这个是苹果端的文件描述;\r\n换行1\r\n换行2";
        } else {
            $last_version = $this->config->item("android_version");
            $down_android = sprintf($this->config->item("download_format"), $last_version, "apk");
            $down_url = site_url($down_android);
            $description = <<<EOF
易控安全分享 {$last_version}发布啦！

1.修复保存登陆的问题；
2.更新意见反馈功能；
3.优化启动，软件启动得更快；
4.更改LOGO，品牌识别度更高。
EOF;
        }

        $res = array(
            'code'          => 0,
            'version'       => $version,
            'url'           => '',
            'description'   => "暂无更新",
            'required'      => false
        );

        if (version_compare($last_version, $version, ">")) {
            $res['code']        = 1;
            $res['version']     = $last_version;
            $res['url']         = $down_url;
            $res['description'] = $description;
        }

        return $this->common_response(0, "", array('data' => $res));
    }
}